# 移除Linux特有的Shebang行（Windows不需要此行）
import pika

try:
    # 建立到本地RabbitMQ的连接
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()

    # 声明消息队列
    channel.queue_declare(queue='hello')

    # 发送消息
    channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
    print(" [x] Sent 'Hello World!'")

finally:
    # 确保连接始终关闭（异常安全）
    if connection and not connection.is_closed:
        connection.close()